<?php

class Kernel_Resource extends Kernel_Component
{
    
    /**
    * @desc Fill this array with fields to get from `system_navigation_item` 
    * table additionally to the `id` and `parent_id`. 
    * 
    * @param array
    */
    public $item_fields = array(); 
    
    /**
     * @desc Menu cach. 
     *
     * @param array
     */
    static private $_menu = array();
    
    
    
    public function __construct($params = array()) 
    {
        parent::__construct($params);
        
        // wrap additional fields
        foreach ($this->item_fields as &$field) {
            $field = '`i`.`' . $field . '`, ';
        }
    }
    
    /**
    * @desc Return specified menu resources. Set active element which ID matches 
    * active param value. 
    * 
    * @param string     $menu
    * @param mixed      $active
    * @return array
    */
    public function menu($name, $active = 0) 
    {
        // search in cach
        if (!array_key_exists($name, self::$_menu)) {
            self::$_menu[$name] = $this->_fetch($name, $active);
        }
        
        return self::$_menu[$name];
    }
    
    /**
    * @desc Return specified menu resources.
    * 
    * @param string     $menu
    * @return array
    */
    protected function _fetch($name, $active) 
    {
        $query = 'SELECT
                         '. implode('', $this->item_fields) . '
                         `i`.`resource_id` `id`, 
                         `i`.`parent_id`, 
                         `r`.`' . __postfix('name') . '` AS `name`,
                         `r`.`url`,
                         IF(`r`.`id` = ' . (int)$active . ', 1, 0) `active`
                    FROM
                         `system_navigation_item` `i`
              INNER JOIN
                         `system_resource` `r`
                      ON
                         `r`.`id` = `i`.`resource_id`
              INNER JOIN
                         `system_navigation` `n`
                      ON
                         `n`.`id` = `i`.`menu_id`
                   WHERE
                         `n`.`name` = "' . database::escape($name) . '"
                ORDER BY
                         `i`.`position`';
        
        return database::fetchAll($query);
    }
    
}